<template>
  <view class="recharge-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-arrow">←</text>
      </view>
      <text class="title">充值中心</text>
    </view>
    
    <!-- 余额显示区域 -->
    <view class="balance-section">
      <view class="balance-card">
        <text class="balance-label">当前余额</text>
        <view class="balance-amount">
          <text class="currency">¥</text>
          <text class="amount">{{ userInfo.balance }}</text>
        </view>
        <text class="balance-desc">可用于AI对话、绘画等服务</text>
      </view>
    </view>
    
    <!-- 充值套餐选择 -->
    <view class="package-section">
      <text class="section-title">选择充值套餐</text>
      <view class="package-grid">
        <view 
          class="package-item" 
          v-for="pkg in packages" 
          :key="pkg.id"
          :class="{ 'selected': selectedPackage === pkg.id }"
          @click="selectPackage(pkg)"
        >
          <view class="package-amount">
            <view class="amount-text">{{ pkg.name }}</view>
            <text class="unit">{{ pkg.originalPrice }} 天</text>
          </view>
          <view class="package-bonus" v-if="pkg.bonus">
            <text class="bonus-text">送{{ pkg.bonus }}元</text>
          </view>
          <view class="package-price">
            <text class="price-text">¥{{ pkg.price }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 支付方式选择 -->
    <view class="payment-section">
      <text class="section-title">选择支付方式</text>
      <view class="payment-list">
        <view 
          class="payment-item" 
          v-for="method in paymentMethods" 
          :key="method.id"
          :class="{ 'selected': selectedPayment === method.id }"
          @click="selectPayment(method.id)"
        >
          <view class="payment-icon">{{ method.icon }}</view>
          <view class="payment-info">
            <text class="payment-name">{{ method.name }}</text>
            <text class="payment-desc">{{ method.desc }}</text>
          </view>
          <view class="payment-radio">
            <view class="radio-circle" :class="{ 'checked': selectedPayment === method.id }"></view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 充值按钮 -->
    <view class="recharge-section" v-if="selectedPackageInfo">
      <view class="recharge-info">
        <text class="info-label">充值金额：</text>
        <text class="info-value">¥{{ selectedPackageInfo.price }}</text>
      </view>
      <view class="recharge-info">
        <text class="info-label">{{selectedPackageData.description}}</text>
      </view>
      
      <button class="recharge-btn" @click="confirmRecharge" :disabled="!canRecharge">
        <text class="btn-text">确认充值</text>
      </button>
    </view>
    
    <!-- 充值说明 -->
    <view class="notice-section">
      <text class="notice-title">充值说明</text>
      <view class="notice-list">
        <text class="notice-item">• 充值金额可用于所有AI服务</text>
        <text class="notice-item">• 赠送金额与充值金额同时到账</text>
        <text class="notice-item">• 充值成功后立即生效，无需等待</text>
        <text class="notice-item">• 如有问题请联系客服</text>
      </view>
    </view>
  </view>
</template>

<script>
import { packageAPI } from '../../utils/api.js'
import { invokeWechatPay, handlePaymentResult, getDefaultPaymentParams } from '../../utils/payment.js'
export default {
  data() {
    return {
      userBalance: 0.00,
      selectedPackage: null,
      selectedPackageData:{},
      selectedPayment: 1,
      packages: [],
      paymentMethods: [
        { id: 1, name: '微信支付', desc: '推荐使用', icon: '' },
      ],
      isLoading: true,
      error: '',
      isWechatEnv: false, // 是否是微信环境
      userInfo:uni.getStorageSync('userInfo'),
      wechatAppId: 'wxd88591414c0627b7' // 微信授权appId
    }
  },
  
  computed: {
    selectedPackageInfo() {
      return this.packages.find(p => p.id === this.selectedPackage) || this.packages[0]
    },
    
    canRecharge() {
      return this.selectedPackage && this.selectedPayment
    }
  },
  
  onLoad() {
    this.checkWechatEnv()
    this.loadUserBalance()
    this.loadPackageList()
  },
  
  methods: {
    // 检测是否是微信环境
    checkWechatEnv() {
      const ua = window.navigator.userAgent.toLowerCase()
      this.isWechatEnv = ua.indexOf('micromessenger') > -1
      console.log('是否微信环境:', this.isWechatEnv)
    },
    
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 加载用户余额
    loadUserBalance() {
      // 这里应该调用API获取用户余额
      // 暂时使用模拟数据
      this.userBalance = 25.50
    },
    
    // 加载套餐列表
    async loadPackageList() {
      try {
        this.isLoading = true
        this.error = ''
        
        const response = await packageAPI.getPackageList()
        
        // 假设接口返回的数据结构中，套餐列表在data字段中
        if (response.code === 0) {
          this.packages = response.data.list
          // 如果有套餐数据，默认选中第一个
          if (this.packages.length > 0) {
            this.selectedPackage = this.packages[0].id
            this.selectedPackageData = this.packages
          }
        } else {
          this.error = '获取套餐列表失败，使用默认套餐'
          console.warn('获取套餐列表失败，使用默认套餐:', response)
        }
      } catch (error) {
        console.error('获取套餐列表异常:', error)
        // 使用默认套餐
        this.packages = [
          { id: 1, amount: 50, price: 50, bonus: 0 },
          { id: 2, amount: 100, price: 100, bonus: 10 },
          { id: 3, amount: 200, price: 200, bonus: 30 },
          { id: 4, amount: 500, price: 500, bonus: 100 },
          { id: 5, amount: 1000, price: 1000, bonus: 250 },
          { id: 6, amount: 2000, price: 2000, bonus: 600 }
        ]
        this.selectedPackage = this.packages[0].id
        this.error = '网络错误，使用默认套餐'
      } finally {
        this.isLoading = false
      }
    },
    
    // 选择充值套餐
    selectPackage(pkg) {
      this.selectedPackage = pkg.id
      this.selectedPackageData = pkg
    },
    
    // 选择支付方式
    selectPayment(paymentId) {
      this.selectedPayment = paymentId
    },
    
    // 确认充值
    confirmRecharge() {
      if (!this.canRecharge) {
        uni.showToast({
          title: '请选择充值套餐和支付方式',
          icon: 'none'
        })
        return
      }
      
      const packageInfo = this.selectedPackageInfo
      
      uni.showModal({
        title: '确认充值',
        content: `确认充值¥${packageInfo.price}？`,
        success: (res) => {
          if (res.confirm) {
            this.processRecharge(packageInfo)
          }
        }
      })
    },
    
    // 处理充值
    async processRecharge(packageInfo) {
      uni.showLoading({
        title: '处理中...'
      })
      
      try {
        // 准备支付参数
        const params = getDefaultPaymentParams({
          packageId: packageInfo.id
        })
        
        console.log('支付请求参数:', params)
        
        // 调用支付接口
        const response = await packageAPI.packagePayment(params)
        
        // 处理支付结果
        const paymentResult = handlePaymentResult(response)
        
        if (paymentResult.success) {
          const payData = paymentResult.data.order.jsApi.params
          
          console.log('支付数据:', payData)
          
          // 如果是微信环境，并且返回了微信支付所需参数，调用微信支付
          if (this.isWechatEnv && payData.timeStamp && payData.nonceStr && payData.package && payData.paySign) {
            try {
              // 调起微信支付
              await invokeWechatPay(payData, (res) => {
                console.log('微信支付成功:', res)
                uni.showToast({
                  title: '支付成功',
                  icon: 'success'
                })
                uni.setStorageSync('isMember',1)
                // 支付成功后延迟返回上一页
                setTimeout(() => {
                  uni.navigateBack()
                }, 1500)
              })
            } catch (wechatError) {
              console.error('微信支付失败:', wechatError)
              uni.showToast({
                title: wechatError.message || '微信支付失败，请重试',
                icon: 'none'
              })
            }
          } else if (payData.payUrl) {
            // 非微信环境，或者没有返回微信支付参数，跳转到支付URL
            console.log('跳转到支付页面:', payData.payUrl)
            window.location.href = payData.payUrl
          } else {
            // 其他情况，提示用户
            uni.showToast({
              title: '支付请求成功，请按照提示完成支付',
              icon: 'none'
            })
            
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack()
            }, 1500)
          }
        } else {
          // 支付请求失败
          console.error('支付请求失败:', paymentResult.message)
          uni.showToast({
            title: paymentResult.message || '支付请求失败，请重试',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('支付异常:', error)
        uni.showToast({
          title: '支付过程中出现异常，请重试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style scoped>
.recharge-container {
  min-height: 100vh;
  background-color: #3A3052;
  padding-bottom: 50px;
}

/* 顶部导航栏 */
.header {
  background-color: #4A4062;
  padding: 16px 20px;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 100;
}

.back-btn {
  position: absolute;
  width: 40px;
  height: 40px;
  background-color: rgba(240, 217, 181, 0.1);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.back-btn:active {
  background-color: rgba(240, 217, 181, 0.2);
  transform: scale(0.95);
}

.back-arrow {
  color: #F0D9B5;
  font-size: 22px;
  font-weight: bold;
}

.title {
  flex: 1;
  color: #FFFFFF;
  font-size: 20px;
  font-weight: 600;
  text-align: center;
}

/* 余额显示区域 */
.balance-section {
  padding: 20px;
}

.balance-card {
  background: linear-gradient(135deg, #F0D9B5 0%, #E8B070 100%);
  border-radius: 16px;
  padding: 24px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(240, 217, 181, 0.3);
}

.balance-label {
  display: block;
  color: #333;
  font-size: 20px;
  margin-bottom: 12px;
}

.balance-amount {
  display: flex;
  align-items: baseline;
  justify-content: center;
  margin-bottom: 8px;
}

.currency {
  color: #333;
  font-size: 26px;
  font-weight: bold;
  margin-right: 4px;
}

.amount {
  color: #333;
  font-size: 50px;
  font-weight: bold;
}

.balance-desc {
  color: #666;
  font-size: 16px;
}

/* 充值套餐选择 */
.package-section {
  padding: 0 20px 20px;
}

.section-title {
  display: block;
  color: #FFFFFF;
  font-size: 20px;
    font-weight: 600;
  margin-bottom: 16px;
}

.package-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.package-item {
  background-color: #4A4062;
  border: 2px solid transparent;
  border-radius: 12px;
  padding: 20px 16px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.package-item.selected {
  border-color: #F0D9B5;
  background-color: rgba(240, 217, 181, 0.1);
}

.package-item:active {
  transform: scale(0.98);
}

.package-amount {
  margin-bottom: 8px;
}

.amount-text {
  color: #F0D9B5;
  font-size: 26px;
  font-weight: bold;
}

.unit {
  color: #F0D9B5;
  font-size: 18px;
    margin-left: 4px;
}

.package-bonus {
  margin-bottom: 12px;
}

.bonus-text {
  color: #4CAF50;
  font-size: 16px;
  background-color: rgba(76, 175, 80, 0.1);
  padding: 4px 8px;
  border-radius: 12px;
}

.package-price {
  color: #FFFFFF;
  font-size: 20px;
    font-weight: 600;
}

/* 支付方式选择 */
.payment-section {
  padding: 0 20px 20px;
}

.payment-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.payment-item {
  background-color: #4A4062;
  border: 2px solid transparent;
  border-radius: 12px;
  padding: 16px;
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.payment-item.selected {
  border-color: #F0D9B5;
  background-color: rgba(240, 217, 181, 0.1);
}

.payment-item:active {
  transform: scale(0.98);
}

.payment-icon {
  font-size: 24px;
  margin-right: 16px;
}

.payment-info {
  flex: 1;
}

.payment-name {
  display: block;
  color: #FFFFFF;
  font-size: 18px;
    font-weight: 500;
  margin-bottom: 4px;
}

.payment-desc {
  color: #8F82A8;
  font-size: 14px;
}

.payment-radio {
  margin-left: 16px;
}

.radio-circle {
  width: 20px;
  height: 20px;
  border: 2px solid #8F82A8;
  border-radius: 50%;
  position: relative;
  transition: all 0.3s ease;
}

.radio-circle.checked {
  border-color: #F0D9B5;
  background-color: #F0D9B5;
}

.radio-circle.checked::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 8px;
  height: 8px;
  background-color: #333;
  border-radius: 50%;
}

/* 充值按钮区域 */
.recharge-section {
  padding: 0 20px 20px;
}

.recharge-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.info-label {
  color: #8F82A8;
  font-size: 16px;
}

.info-value {
  color: #FFFFFF;
  font-size: 18px;
    font-weight: 600;
}

.info-value.bonus {
  color: #4CAF50;
}

.info-value.total {
  color: #F0D9B5;
  font-size: 18px;
}

.recharge-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #F0D9B5 0%, #E8B070 100%);
  border: none;
  border-radius: 25px;
  margin-top: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.recharge-btn:active {
  transform: scale(0.98);
}

.recharge-btn:disabled {
  background: #666;
  cursor: not-allowed;
}

.btn-text {
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

/* 充值说明 */
.notice-section {
  padding: 0 20px;
}

.notice-title {
  display: block;
  color: #8F82A8;
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
}

.notice-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.notice-item {
  color: #8F82A8;
  font-size: 14px;
  line-height: 1.4;
}
</style>
